<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class TicketorderController extends ThinkController{
	/**
     * 显示指定模型列表数据
     * @param  String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
	public function lists($model = null, $p = 0){
		$model || $this->error('模型名标识必须！');
		$page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');

        $map = array();
        // $map['ticket_order.status'] = array('neq',4);
        $map['ticket_order.status'] = 1;

        $begin_time = $_GET['begin_time']?strtotime($_GET['begin_time']):strtotime("-0 year -3 month -0 day");
        $end_time = $_GET['end_time']?strtotime($_GET['end_time'])+3600*24:time();
        $exhibition_id = strlen($_GET['ex_id'])>0?$_GET['ex_id']:null;
        $ticket_id = strlen($_GET['ticket_id'])>0?$_GET['ticket_id']:null;

        //filter放进默认变量 以供前台显示
        $default_filter['begin_time'] = $_GET['begin_time']?$_GET['begin_time']:date('Y-m-d',strtotime("-0 year -3 month -0 day"));
        $default_filter['end_time'] = $_GET['end_time']?$_GET['end_time']:date('Y-m-d');
        $default_filter['exhibition_id'] = $_GET['exhibition_id']?$_GET['exhibition_id']:null;
        $default_filter['ticket_id'] = $_GET['ticket_id']?$_GET['ticket_id']:null;

        if($exhibition_id){
          $map['ticket.exhibition_id'] = $exhibition_id;
        }
        if($ticket_id){
          $map['ticket_order.ticket_id'] = $ticket_id;
        }

        /* 查询所有订单记录 */
        $name = parse_name(get_table_name($model['id']), true);
        $total = D($name)
        ->field('ticket_order.*,ticket.price,ticket.price_activity,payment.price as totalprice')
        ->where("ticket_order.create_time >= ".$begin_time." and ticket_order.create_time < ".$end_time)
        ->join('ticket on ticket.id = ticket_order.ticket_id','left')
        ->join('payment on payment.id = ticket_order.payment_num','left')
        ->where($map)
        // ->relation(true)
        ->select();

        $total_amount  = 0;
        $total_price = 0;
        $total_redeemed = 0;
        $total_redeem_price = 0;

        foreach ($total as $key => $value) {
          # code...
          //默认现场购票都是非会员票
          $value['totalprice']=$value['totalprice']==null?$value['price']*$value['amount']:$value['totalprice'];
          $single_price = $value['totalprice']==null?$value['price']:$value['totalprice']/$value['amount'];
          $total_amount = $total_amount + $value['amount'];
          // $total_redeemed = $total_redeemed + count($value['Redeemcode']);
          $total_price = $total_price + $value['totalprice'];
          // $total_redeem_price = $total_redeem_price + $single_price*count($value['Redeemcode']);
        }

        /* 查询所有兑换记录 */

        $filter_count['order_amount'] = $count;
        $filter_count['total_amount'] = $total_amount;
        $filter_count['total_price'] = $total_price;

        $total_redeemed_codes = M('ticket_redeem_code')
        ->field('ticket_redeem_code.*,ticket.id as ticket_id')
        ->join('ticket_order on ticket_order.id = ticket_redeem_code.ticket_order_id','left')
        ->join('ticket on ticket.id = ticket_order.ticket_id','left')
        ->where("ticket_redeem_code.redeem_time >= ".$begin_time." and ticket_redeem_code.redeem_time < ".$end_time)
        ->where(array('ticket_redeem_code.status'=>'1'))
        ->where($map)
        ->count();

        $total_redeemed_price = M('ticket_redeem_code')
        ->field('payment.price as totalprice,ticket_order.price,ticket_order.amount')
        ->join('ticket_order on ticket_order.id = ticket_redeem_code.ticket_order_id','left')
        ->join('ticket on ticket.id = ticket_order.ticket_id','left')
        ->join('payment on payment.id = ticket_order.payment_num','left')
        ->where("ticket_redeem_code.redeem_time >= ".$begin_time." and ticket_redeem_code.redeem_time < ".$end_time)
        ->where(array('ticket_redeem_code.status'=>1))
        ->where($map)
        ->select();
        
        foreach($total_redeemed_price as $key => $value){
          $single_price = $value['totalprice']==null?$value['price']:$value['totalprice']/$value['amount'];
          $total_redeem_price = $total_redeem_price + $single_price;
        }
        $filter_count['total_redeemed'] = $total_redeemed_codes;
        $filter_count['total_redeem_price'] = $total_redeem_price;

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
        	if(trim($value) === ''){
        		continue;
        	}
            // 字段:标题:链接
        	$val      = explode(':', $value);
            // 支持多个字段显示
        	$field   = explode(',', $val[0]);
        	$value    = array('field' => $field, 'title' => $val[1]);
        	if(isset($val[2])){
                // 链接信息
        		$value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
        		preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
        	}
        	if(strpos($val[1],'|')){
                // 显示格式定义
        		list($value['title'],$value['format'])    =   explode('|',$val[1]);
        	}
        	foreach($field as $val){
        		$array	=	explode('|',$val);
        		$fields[] = $array[0];
        	}
        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        // $key	=	$model['search_key']?$model['search_key']:'title';
        // if(isset($_REQUEST[$key])){
        // 	$map[$key]	=	array('like','%'.$_GET[$key].'%');
        // 	unset($_REQUEST[$key]);
        // }
        //条件搜索
        // foreach($_REQUEST as $name=>$val){
        // 	if(in_array($name,$fields)){
        //     if($val!=''){
        //       $map[$name] = $val;
        //     }
        // 	}
        // }
        $row  = empty($model['list_row']) ? 10 : $model['list_row'];

        //读取模型数据列表
        if($model['extend']){
          $name   = get_table_name($model['id']);
          $parent = get_table_name($model['extend']);
          $fix    = C("DB_PREFIX");

          $key = array_search('id', $fields);
          if(false === $key){
            array_push($fields, "{$fix}{$parent}.id as id");
          } else {
            $fields[$key] = "{$fix}{$parent}.id as id";
          }

          /* 查询记录数 */
          $count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
          $data   = M($parent)
          ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
          /* 查询指定字段，不指定则查询所有字段 */
          ->field(empty($fields) ? true : $fields)
                // 查询条件
          ->where("create_time >= ".$begin_time." and create_time < ".$end_time)
          ->where($map)
          /* 默认通过id逆序排列 */
          ->order("{$fix}{$parent}.id DESC")
          /* 数据分页 */
          ->page($page, $row)
          /* 执行查询 */
          ->select();

        } else {
          if($model['need_pk']){
            in_array('id', $fields) || array_push($fields, 'id');
          }
          $name = parse_name(get_table_name($model['id']), true);
          
          $data = M($name)
          /* 查询指定字段，不指定则查询所有字段 */
          // ->field(empty($fields) ? true : $fields)
          ->field('ticket_order.*')
          /*join */
          ->join('ticket on ticket.id = ticket_order.ticket_id','left')
          // ->join('ticket on ticket.id = ticket_order.ticket_id')
                // 查询条件
          ->where("create_time >= ".$begin_time." and create_time < ".$end_time)
          ->where($map)

          /* 默认通过id逆序排列 */
          ->order($model['need_pk']?'id DESC':'')
          /* 数据分页 */
          ->page($page, $row)
          /* 执行查询 */
          ->select();


          /* 查询记录总数 */
          $count = M($name)
          ->field('ticket_order.*')
          ->join('ticket on ticket.id = ticket_order.ticket_id','left')
          ->where("create_time >= ".$begin_time." and create_time < ".$end_time)
          ->where($map)
          ->count();
        }

        //分页
        if($count > $row){
        	$page = new \Think\Page($count, $row);
        	$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        	$this->assign('_page', $page->show());
        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        //所有展览
        $exhibitions = M('exhibition')->select();
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->assign('count', $count);
        $this->assign('filter_count', $filter_count);
        $this->assign('exhibitions', $exhibitions);
        $this->assign('default_filter', $default_filter);
        $this->meta_title = $model['title'].'列表';

        $this->display($model['template_list']);
      }

      public function del($model = null, $ids=null){
      	$model = M('Model')->find($model);
      	$model || $this->error('模型不存在！');

      	$ids = array_unique((array)I('ids',0));

      	if ( empty($ids) ) {
      		$this->error('请选择要操作的数据!');
      	}

      	$Model = M(get_table_name($model['id']));
      	$map = array('id' => array('in', $ids) );
      	if($Model->where($map)->delete()){
      		$this->success('删除成功');
      	} else {
      		$this->error('删除失败！');
      	}
      }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model='Document'){
    	return parent::setStatus($model);
    }
    
    public function edit($model = null, $id = 0){
        //获取模型信息
    	$model = M('Model')->find($model);
    	$model || $this->error('模型不存在！');

    	if(IS_POST){
    		$Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
    		$Model  =   $this->checkAttr($Model,$model['id']);
    		if($Model->create() && $Model->save()){
    			$this->success('保存'.$model['title'].'成功！', U('lists?model='.$model['name']));
    		} else {
    			$this->error($Model->getError());
    		}
    	} else {
    		$fields     = get_model_attribute($model['id']);

            //获取数据
    		$data       = M(get_table_name($model['id']))->find($id);
    		$data || $this->error('数据不存在！');

            //查找展览票券信息
        $data['ticket'] = M('ticket')->where(array('id'=>$data['ticket_id']))->find();
        $re_exhibition = M('exhibition')->where(array('id'=>$data['ticket']['exhibition_id']))->find();
        $data['exhibition_name'] = $re_exhibition['name'];
            //查找兑换码信息
        $re_codes = M('ticket_redeem_code')
        ->where(array('ticket_order_id'=>$data['id']))
        ->select();
        $data['codes'] = $re_codes;

        foreach ($data['codes'] as $key => $value) {
                # code...
          if($value['redeem_time']){
            $data['codes'][$key]['redeem_time'] = date("Y-m-d H:s",$data['codes'][$key]['redeem_time']);
          }
        }

            //查找用户信息
        if($data['visitor_id']){
          $re_visitor = M('visitor')->find($data['visitor_id']);
          $data['visitor_phone'] = $re_visitor['visitor_phone'];
        }else{
          $data['visitor_phone'] = null;
        }
        

        $this->assign('model', $model);
        $this->assign('fields', $fields);
        $this->assign('data', $data);
        $this->meta_title = '编辑'.$model['title'];
        $this->display($model['template_edit']?$model['template_edit']:'');
      }
    }

    public function add($model = null){
        //获取模型信息
    	$model = M('Model')->where(array('status' => 1))->find($model);
    	$model || $this->error('模型不存在！');
    	if(IS_POST){
    		$Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
    		$Model  =   $this->checkAttr($Model,$model['id']);
    		if($Model->create() && $Model->add()){
    			$this->success('添加'.$model['title'].'成功！', U('lists?model='.$model['name']));
    		} else {
    			$this->error($Model->getError());
    		}
    	} else {

    		$fields = get_model_attribute($model['id']);

    		$this->assign('model', $model);
    		$this->assign('fields', $fields);
    		$this->meta_title = '新增'.$model['title'];
    		$this->display($model['template_add']?$model['template_add']:'');
    	}
    }

    public function data_export(){//后台导出
      $begin_time = $_POST['begin_time']?strtotime($_POST['begin_time']):000000000;
      $end_time = $_POST['end_time']?strtotime($_POST['end_time'])+3600*24:9999999999;
      $exhibition_id = strlen($_POST['ex_id'])>0?$_POST['ex_id']:null;
      $status = strlen($_POST['status'])>0?$_POST['status']:null;
      $ticket_id = strlen($_POST['ticket_id'])>0?$_POST['ticket_id']:null;
      if($exhibition_id){
        $map['ticket.exhibition_id'] = $exhibition_id;
      }
      if($status){
        $map['ticket_redeem_code.status'] = array('gt',$status);
      }
      if($ticket_id){
        $map['ticket_order.ticket_id'] = $ticket_id;
      }
      // $data = M('ticket_order')
      // ->field('ticket_order.*,exhibition.name as ex_name,ticket.name as ticket_name,ticket.price,visitor.name as visitor_name,visitor.phone as visitor_phone,visitor.nickname')
      // ->where("create_time >= $begin_time and create_time < $end_time")
      // ->join('ticket on ticket.id = ticket_order.ticket_id','left')
      // ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
      // ->join('visitor on visitor.id = ticket_order.visitor_id','left')
      // ->select();

      $data = M('ticket_redeem_code')
      ->field('ticket_redeem_code.*,ticket_order.ticket_id,ticket_order.order_num,ticket_order.payment,ticket_order.amount,exhibition.name as ex_name,ticket.name as ticket_name,ticket.price,visitor.name as visitor_name,visitor.phone as visitor_phone,visitor.nickname,payment.price as total_price')
      ->where($map)
      ->where("ticket_redeem_code.create_time >= $begin_time and ticket_redeem_code.create_time < $end_time")
      ->join('ticket_order on ticket_order.id = ticket_redeem_code.ticket_order_id','left')
      ->join('ticket on ticket.id = ticket_order.ticket_id','left')
      ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
      ->join('visitor on visitor.id = ticket_order.visitor_id','left')
      ->join('payment on payment.id = ticket_order.payment_num','left')
      ->select();
      foreach ($data as $key => $value) {
        # 支付方式
        if($value['payment']=='1'){
          $data[$key]['payment'] = '微信支付';
        }else if($value['payment']=='2'){
          $data[$key]['payment'] = '支付宝支付';
        }else{
          $data[$key]['payment'] = '现金支付';
        }
        # 状态
        if($value['status']=='0'){
          $data[$key]['status'] = '未兑换';
        }else{
          $data[$key]['status'] = '已兑换';
        }
        // 时间
        $data[$key]['create_time'] = date('Y-m-d H:i:s',$data[$key]['create_time']);
        $data[$key]['redeem_time'] = $data[$key]['redeem_time']?date('Y-m-d H:i:s',$data[$key]['redeem_time']):null;
        $data[$key]['price'] = $data[$key]['total_price']==null?$data[$key]['price']:$data[$key]['total_price']/$data[$key]['amount'];
      }
      $excel = new \Think\Excel();
      // $image = array('avatar'=>'image');
      $excel_title = array('订单编号','兑换码','用户姓名','用户昵称','用户手机','展览','票务名','票价/元','支付方式','状态','购买时间','兑换时间');
      $row_keys = array('order_num','redeem_code','visitor_name','nickname','visitor_phone','ex_name','ticket_name','price','payment','status','create_time','redeem_time');
      $headers_types['price'] = 'number';
      $excel->prepareDownloadExcel($data,$excel_title,$row_keys,'票务订单',$headers_types);
    }

    public function getTickets(){
      $ex_id = I('get.ex_id');
      if(!$ex_id){
        return;
      }
      $tickets = M('ticket')->where(array('exhibition_id'=>$ex_id))->select();
      $this->success($tickets);
    }
  }